﻿using System;
using System.Linq;

namespace DBProvider.Providers
{
	public class NewsProvider:INewsProvider
	{
		#region INewsProvider Members

		public SiteNew CreateSiteNew(SiteNew theNewSiteNew, out string msg)
		{
			if(theNewSiteNew == null)
			{
				throw new ArgumentNullException();
			}

			msg = string.Empty;
			SiteNew result = null;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var isExist = db.SiteNews.Count(n => n.NewsTitle == theNewSiteNew.NewsTitle) > 0;

					if(!isExist)
					{
						db.SiteNews.InsertOnSubmit(theNewSiteNew);
						db.SubmitChanges();

						theNewSiteNew = db.SiteNews.SingleOrDefault(n => n.NewsTitle == theNewSiteNew.NewsTitle);
					}
					else
					{
						msg = "相同的标题已存在";
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public bool UpdateSiteNew(SiteNew theSiteNew)
		{
			if(theSiteNew == null || theSiteNew.NewsID <= 0)
			{
				throw new ArgumentException();
			}

			var result = false;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var dbSiteNew = db.SiteNews.SingleOrDefault(n => n.NewsID == theSiteNew.NewsID);

					if(dbSiteNew != null)
					{
						dbSiteNew.NewsContent = theSiteNew.NewsContent;

						db.SubmitChanges();

						result = true;
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public bool DeleteSiteNew(int siteNewID)
		{
			if(siteNewID <= 0)
			{
				throw new ArgumentOutOfRangeException();
			}

			var result = false;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var dbSiteNew = db.SiteNews.SingleOrDefault(n => n.NewsID == siteNewID);

					if(dbSiteNew != null)
					{
						db.SiteNews.DeleteOnSubmit(dbSiteNew);
						db.SubmitChanges();

						result = true;
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public SiteNew GetSiteNew(int siteNewID)
		{
			if(siteNewID <= 0)
			{
				throw new ArgumentOutOfRangeException();
			}

			SiteNew result = null;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					result = db.SiteNews.SingleOrDefault(n => n.NewsID == siteNewID);
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public SiteNew GetSiteNewByTitle(string title)
		{
			if(string.IsNullOrEmpty(title))
			{
				throw new ArgumentException();
			}

			SiteNew result = null;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					result = db.SiteNews.SingleOrDefault(n => n.NewsTitle == title);
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		#endregion
	}
}
